import choose from '@/assets/c_choose.png';
import nochoose from '@/assets/c_no_choose.png';
import woman from '@/assets/s_woman.png';
import { handleParams, handleResiterByContact, sendMobileCodeNT } from '@/services/login';
import { formatNumber } from '@/utils';
import { genderOptions, phonePattern } from '@/utils/common';
import { useRequest } from 'ahooks';
import { Button, Divider, Flex, Form, Input, message, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import './index.less';

let timer: any = null;
const Contact: React.FC<{
  className?: string;
  bottomWord?: React.ReactNode;
  needTop?: boolean;
  title?: React.ReactNode;
}> = ({ className, needTop = true, title, bottomWord }) => {
  const intl = useIntl();
  const isEn = intl.locale == 'en-US';
  const [form] = Form.useForm();
  const sex = Form.useWatch('sex', form);
  const values = Form.useWatch([], form);
  const [submittable, setSubmittable] = useState<boolean>(false);
  const [count, setCount] = useState(0);
  const { data } = useRequest(() => handleParams({ code: 'Auth_Amount' }), { ready: true });
  const configList = data?.data?.Auth_Amount[0].value.split(',').map((item: any) => {
    return {
      label: formatNumber(item),
      value: item,
    };
  });
  //  防止频繁点击
  const [isClick, setIsClick] = useState(false);
  // 是否
  const [isFirstClick, setIsFirstClick] = useState(false);
  useEffect(() => {
    if (count == 59) {
      timer = setInterval(() => setCount((t) => t - 1), 1000);
    } else if (count <= 0) {
      clearInterval(timer);
    }
  }, [count]);

  useEffect(() => {
    if (values && Object.keys(values).length > 0) {
      form
        .validateFields({ validateOnly: true })
        .then(() => {
          setSubmittable(true);
        })
        .catch(() => setSubmittable(false));
    } else {
      setSubmittable(false);
    }
  }, [form, values]);

  const sendSuc = () => {
    setCount(59);
    setIsClick(false);
    setIsFirstClick(true);

    message.success(intl.formatMessage({ id: 'home.send_suc' }));
  };
  return (
    <div className={`common_contact ${className}`}>
      {needTop ? (
        <div className="common_contact_top">
          <div style={{ fontSize: 16, color: '#fff', lineHeight: '18px', width: 195 }}>
            {intl.formatMessage({ id: 'home.contact_onebyone' })}
          </div>
          <img src={woman} className="common_contact_top_woman" />
        </div>
      ) : null}
      <div className="common_contact_form">
        <div>{title}</div>
        <Form
          onFinish={async (value) => {
            const { phone, captcha } = value;
            const { code } = await handleResiterByContact({ mobile: phone, captcha });
            if (code === '100200') {
              message.success(intl.formatMessage({ id: 'home.contact_suc' }));
            }
          }}
          form={form}
          colon={false}
          requiredMark={false}
          labelCol={{ span: 0 }}
        >
          <Form.Item
            rules={[{ required: true }]}
            name="name"
            label={intl.formatMessage({ id: 'home.contact_name' })}
          >
            <Input
              style={{ color: '#0f294d', height: 40 }}
              placeholder={intl.formatMessage({ id: 'home.contact_name' })}
            />
          </Form.Item>
          <Flex style={{ marginBottom: 19 }} align="center" justify="space-between">
            <Form.Item rules={[{ required: true }]} name="sex" hidden />
            <Flex gap={10} justify="center" style={{ width: '100%' }}>
              {genderOptions.map((item) => {
                const { label, value } = item;
                const isActive = sex == value;
                return (
                  <Flex
                    key={value}
                    gap={8}
                    onClick={() => {
                      form.setFieldValue('sex', value);
                    }}
                    justify="center"
                    align="center"
                    style={{
                      borderRadius: 6,
                      border: `1px solid ${isActive ? '#d7e3ff' : '#d9d9d9'}`,
                      height: 40,
                      cursor: 'pointer',
                      backgroundColor: isActive ? '#edf2ff' : '',
                      color: isActive ? '#333' : '#868686',
                      flex: 1,
                    }}
                  >
                    <img width={16} height={16} src={isActive ? choose : nochoose} />
                    {label}
                  </Flex>
                );
              })}
            </Flex>
          </Flex>

          <Form.Item
            label={intl.formatMessage({
              id: 'login.phone.input',
            })}
            rules={[{ required: true }, phonePattern]}
            name="phone"
            validateTrigger="onBlur"
          >
            <Input
              prefix={<div style={{ color: '#000', marginRight: 15 }}>+852</div>}
              style={{ height: 40 }}
              placeholder={intl.formatMessage({
                id: 'login.phone.input',
              })}
            />
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, curValues) => prevValues.phone !== curValues.phone}
          >
            {({ getFieldValue }) => {
              const mobile = getFieldValue('phone');
              return (
                <Form.Item
                  label={intl.formatMessage({ id: 'login.captcha' })}
                  rules={[{ required: true }]}
                  name="captcha"
                >
                  <Input
                    suffix={
                      <>
                        <Divider type="vertical" />
                        <Button
                          disabled={!mobile || isClick || !!count}
                          onClick={async () => {
                            if (isClick || !!count) {
                              return false;
                            }

                            setIsClick(true);
                            const params = { valType: '3' };
                            try {
                              await sendMobileCodeNT({
                                mobile,
                                ...params,
                              });

                              sendSuc();
                            } catch {
                              setIsClick(false);
                            }
                          }}
                          className="login_code_btn"
                          style={{
                            border: 'none',
                            background: 'none',
                            padding: '0',
                            boxShadow: 'none',
                          }}
                        >
                          {count == 0
                            ? isFirstClick
                              ? intl.formatMessage({ id: 'login.phone.send' })
                              : intl.formatMessage({ id: 'login.get' })
                            : intl.formatMessage({ id: 'login.count' }, { count: count })}
                        </Button>
                      </>
                    }
                    style={{ height: 40 }}
                    placeholder={intl.formatMessage({ id: 'login.captcha' })}
                  />
                </Form.Item>
              );
            }}
          </Form.Item>
          <Form.Item
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'home.choose_loan_scope',
                }),
              },
            ]}
            name="amount"
          >
            <Select
              options={configList}
              style={{ height: 40 }}
              placeholder={intl.formatMessage({
                id: 'home.loan_scope',
              })}
            />
          </Form.Item>
          <Form.Item>
            <Button
              block
              disabled={!submittable}
              htmlType="submit"
              type="primary"
              className="contact_modal_btn"
              style={{
                height: 40,

                fontSize: 18,
                fontWeight: 400,
              }}
            >
              <div>{intl.formatMessage({ id: 'home.contact_now' })}</div>
            </Button>
          </Form.Item>
        </Form>
        <div
          className="bottom_word"
          style={{
            textAlign: 'center',
            lineHeight: '16px',
            fontSize: 12,
            color: '#0f294d',
            marginTop: -10,
          }}
        >
          {bottomWord ? (
            bottomWord
          ) : (
            <>
              {intl.formatMessage({ id: 'home.contact_submit2' })}
              {isEn ? <div>{intl.formatMessage({ id: 'home.contact_submit1' })}</div> : null}{' '}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default Contact;
